<?php

/**
 * @author	juxuan
 * @time	2011-1-1
 *
 **/


//用户注册
function register(){
	
	require_once ('mysql_connect.php');
	
	$username = trim(stripslashes($_REQUEST['username']));
	$userpsw = trim(stripslashes($_REQUEST['userpsw']));
	$email = trim(stripslashes($_REQUEST['email']));
	
	$query = "select id from user where name = '".$username."'";
	mysql_query("set names utf8");
	$result = @mysql_query($query);
	$row = mysql_fetch_array($result,MYSQL_ASSOC);
	if($row){
		header('Content-Type:text/html;charset=utf-8');
		echo "该用户名已被注册！";
		exit();
	}
	else{
		$insert = "insert into user(name, email,password) values('$username','$email',SHA('$userpsw'))";
		$result = mysql_query($insert);
		if($result){
			header('Content-Type:text/html;charset=utf-8');
			echo '注册成功！';
			exit();
		}
	}
}

//用户登录
function login(){
	require_once ('mysql_connect.php');
	
	$username = trim(stripslashes($_REQUEST['username']));
	$userpsw = trim(stripslashes($_REQUEST['userpsw']));
	
	//$query = "select id,name from user where (name='$username' and password=SHA('$userpsw'))";
	$query = "select id,name,password from user where name='$username'";
	$result = mysql_query($query) or trigger_error("Mysql Error:".mysql_error());
	if(@mysql_num_rows($result) == 1){
		$row = mysql_fetch_array($result,MYSQL_NUM);
		mysql_free_result($result);
		mysql_close();
		$psw = $row[2];
		if($psw == sha1($userpsw)){
			setcookie('username',$row[1]);
			setcookie('userid',$row[0]);
			$url = 'loggedin.php';
			ob_end_clean();
			header('Content-Type:text/html;charset=utf-8');
			header("Location: $url");
			exit();
		}
		else{
			header('Content-Type:text/html;charset=utf-8');
			echo '用户名和密码不匹配！';
		}
		
		
	}else{
		header('Content-Type:text/html;charset=utf-8');
		echo '该帐户不存在！';
	}
	
}

login();

//session authentication
function sessionAuth(){
	session_start();
	
	if(!isset($_SESSION['username'])){
		$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
		
		if((substr($url,-1) == '/') OR (substr($url,-1) == '\\')){
				$url = substr($url,0,-1);
		}
		
		$url .= 'index.php';
		header("Location: $url");
		exit();
	}
	
	echo "You are now logged in,{$_SESSION['username']}!";
	
}

//cookie authentication
function cookieAuth(){
	#User is redirected here from login.php
	
	if(!isset($_COOKIE['username'])){
		
		$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
		
		if((substr($url,-1) == '/') OR (substr($url,-1) == '\\')){
			$url = substr($url,0,-1);
		}
		
		$url .= 'index.php';
		header("Location: $url");
		exit();
	}
	
	echo "You are now logged in,{$_COOKIE['username']}!";
	
}




?>
